package com.example.sharesinfo.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import com.example.sharesinfo.bmob.BmobManager;
import com.example.sharesinfo.helper.LitePalHelper;
import com.example.sharesinfo.manager.CloudManager;
import com.example.sharesinfo.utils.SpUtils;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import org.litepal.LitePal;

public class BaseApp extends Application {
    private RefWatcher refWatcher;
    /**
     * Application的优化
     * 1.必要的组件在程序的主页去初始化
     * 2.如果组件一定要在App中初始化，尽肯能的延时
     * 3.非必要的组件，子线程中初始化
     */
    @Override
    public void onCreate() {
        super.onCreate();
        //LeakCanary的初始化
        //refWatcher= setupLeakCanary();
        //只在主进程中初始化
        if (getApplicationInfo().packageName.equals(
                getCurProcessName(getApplicationContext()))) {
            SpUtils.getInstance().initSp(this);
            BmobManager.getInstance().initBmob(this);
            CloudManager.getInstance().initCloud(this);
            LitePal.initialize(this);
        }
    }

    //
//    private RefWatcher setupLeakCanary() {
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            return RefWatcher.DISABLED;
//        }
//        return LeakCanary.install(this);
//    }
//
//    public static RefWatcher getRefWatcher(Context context) {
//        BaseApp leakApplication = (BaseApp) context.getApplicationContext();
//        return leakApplication.refWatcher;
//    }

    /**
     * 获取当前进程名
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager)
                context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess :
                activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }
}
